package org.itboys.mobile.service.mongo.weixin;


import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.ZhongBaoChat;
import org.itboys.mobile.entity.mongo.ZhongBaoChatGroup;
import org.itboys.mobile.entity.mongo.ZhongBaoMessage;
import org.itboys.mobile.entity.mongo.project.ZhongBaoProject;
import org.itboys.mobile.entity.mongo.project.ZhongBaoProjectSign;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.acl.Group;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：众包_微信_聊天_组_service
 */
@Service
public class ZhongBaoWeiXinChatGroupService extends BaseMongoService<ZhongBaoChatGroup> {
    @Autowired
    private ZhongBaoWeiXinMessageService messageService;
    @Autowired
    private ZhongBaoWeiXinProjectService projectService;
    @Autowired
    private SundayWeiXinMemberService memberService;
    @Autowired
    private ZhongBaoWeiXinChatService chatService;
    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<ZhongBaoChatGroup> getEntityClass() {
        return ZhongBaoChatGroup.class;
    }

    /**
     * 创建聊天组
     * @param projectId
     * @param memberIds
     */

    public long  generateGroup(Long memberId1,Long memberId2,Long projectId,String memberIds){
        String title ="";
            if(LongUtil.isNotZreo(projectId)){
                title=projectService.getById(projectId).getName()+"的群聊";
            }else{
                projectId=0l;
                title=memberService.getById(memberId1).getNickName()+"和"+memberService.getById(memberId2).getNickName()+"群聊";
            }
            ZhongBaoChatGroup group=  new ZhongBaoChatGroup(projectId,title,memberIds);
            super.save(group);
            return group.getId();

    }
    /**
     *  获取聊天组列表。暂时不分页
     *  1，需要根据用户匹配未读消息的数量
     *  2，按最近修改时间时间排序
     * @param request
     * @param memberId
     */
   public List<ZhongBaoChatGroup> getGroup(HttpServletRequest request,Long memberId){
        Map<String,Object> param = ParamUtil.packageMongoExactParam(request,"title");
        param.put("sort","ut");
        param.put("order","DESC");
        param.put("contains:memberIds",memberId);
       // logger.info("AAAAAAAAAAAAAAAAAAAAA");
        List<ZhongBaoChatGroup> groups=super.list(param);
        //logger.info("0000000000000000--"+groups.size());
        //匹配未读消息数量
        List<Long> groupIds = new ArrayList<>();
        for(ZhongBaoChatGroup group:groups){
            groupIds.add(group.getId());
        }
        if(ListUtil.isNotNull(groupIds)){
            param.clear();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("otherId in",groupIds);
            param.put("status", SundayCommonConstants.NO);
            List<ZhongBaoMessage> messages =messageService.list(param);
            for(ZhongBaoChatGroup group:groups){
                Integer number=0;
                for(ZhongBaoMessage message:messages){
                    if(LongUtil.isNotZreo(message.getOtherId())&&
                            message.getOtherId().longValue()==group.getId()){
                        number++;
                    }
                }
                group.setNumber(number);
            }
        }
        return groups;

   }

    /**
     * 打开聊天群组。自动该用户已读所有的聊天消息
     * @param memberId
     * @param groupId
     */
    public  List<ZhongBaoChat> open(Long memberId,Long groupId){
        ZhongBaoChatGroup group = super.getById(groupId);
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("otherId",group.getId());
        param.put("status", SundayCommonConstants.NO);
        param.put("memberId",memberId);
        List<ZhongBaoMessage> messages = messageService.list(param);
        for(ZhongBaoMessage message:messages){
            message.setStatus(SundayCommonConstants.YES);
        }
        if(ListUtil.isNotNull(messages)){
            messageService.batchUpdate(messages);
        }
        //2017年11月13日，增加。返回所有的聊天记录
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("groupId",groupId);
        param.put("sort","ct");
        param.put("order","desc");
        return chatService.list(param);
    }

    /**
     * 加入讨论组。报名通过后
     * @param memberId
     * @param groupId
     */
    public void join(Long memberId,Long groupId){
        ZhongBaoChatGroup group = super.getById(groupId);
        super.update(groupId,"memberIds",group.getMemberIds()+","+memberId);
    }

    /**
     * 留言
     * @param memberId
     * @param groupId 从群聊进入
     * @param content
     */
    public void chat(Long memberId,Long groupId,String content){
        ZhongBaoChatGroup group = super.getById(groupId);;
       /* if(LongUtil.isNotZreo(groupId)){
            group=super.getById(groupId);
        }else{
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("projectId",projectId);
            List<ZhongBaoChatGroup> groups= super.list(param);
            if(ListUtil.isNotNull(groups)){
                group=groups.get(0);
            }
        }*/
        SundayMember member= memberService.getById(memberId);
        ZhongBaoChat chat = new ZhongBaoChat(groupId,memberId, member.getNickName(), member.getImage(), content);
        chatService.save(chat);
        //给组内的每个人发一条未读消息，不包含留言人

       // List<Long> memberIds = new ArrayList<>();
        for(String groupMemberIdStr:group.getMemberIds().split(",")){
            if(StringUtils.isNotEmpty(groupMemberIdStr)){
                messageService.generateMessage(
                        Long.valueOf(groupMemberIdStr),
                        member.getId(),
                        group.getProjectId(),
                        SundayCommonConstants.zhongbao_message_type_word,
                        "留言",
                        content,
                        group.getId(),
                        0l);
            }
        }
      }


}
